<?php

/**
 * 从Tushare Pro API获取股票日线数据
 * @param string $token 您的Tushare token
 * @param string $ts_code 股票代码，如 '601288.SH'
 * @param string $start_date 开始日期，格式 '20240101'
 * @param string $end_date 结束日期，格式 '20241231'
 * @return array API返回的JSON数据
 */
function getTushareDailyData($token, $ts_code, $start_date = '', $end_date = '') {
	// 1. 准备API请求数据
	$api_url = "http://api.tushare.pro";
	
	$post_data = [
		"api_name" => "daily",
		"token" => $token,
		"params" => [
			"ts_code" => $ts_code
		],
		"fields" => "ts_code,trade_date,open,high,low,close" // 可以指定字段，如 "ts_code,trade_date,open,high,low,close,vol"
	];
	
	// 添加可选的时间参数
	if (!empty($start_date)) {
		$post_data['params']['start_date'] = $start_date;
	}
	if (!empty($end_date)) {
		$post_data['params']['end_date'] = $end_date;
	}
	
	// 2. 初始化cURL
	$ch = curl_init();
	
	// 3. 设置cURL选项
	curl_setopt_array($ch, [
		CURLOPT_URL => $api_url,
		CURLOPT_RETURNTRANSFER => true,     // 将响应作为字符串返回，而不是直接输出
		CURLOPT_POST => true,               // 使用POST方法
		CURLOPT_POSTFIELDS => json_encode($post_data), // 将数据编码为JSON
		CURLOPT_HTTPHEADER => [
			'Content-Type: application/json',
			'User-Agent: PHP-Tushare-Client/1.0'
		],
		CURLOPT_TIMEOUT => 30,              // 超时时间（秒）
	]);
	
	// 4. 执行请求并获取响应
	$response = curl_exec($ch);
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	$curl_error = curl_error($ch);
	
	// 5. 关闭cURL资源
	curl_close($ch);
	
	// 6. 检查请求是否成功
	if ($response === false) {
		throw new Exception("cURL请求失败: " . $curl_error);
	}
	
	if ($http_code !== 200) {
		throw new Exception("HTTP错误代码: " . $http_code);
	}
	
	// 7. 解析JSON响应
	$result = json_decode($response, true);
	
	if (json_last_error() !== JSON_ERROR_NONE) {
		throw new Exception("JSON解析失败: " . json_last_error_msg());
	}
	
	return $result;
}

// 使用示例
try {
	$token = "70a2df7552c0ea045f9025612984ad26edf8cef37f035ac70f0d9853";
	$ts_code = "601288.SH";
	// $ts_code = "001285.SZ";
	
	// $data = getTushareDailyData($token, $ts_code);							// 获取指定股票的最近的数据（获取到它上市，或达到6000条数据）
	$data = getTushareDailyData($token, $ts_code, '20240101', '20251021');	// 或者指定日期范围
	// $data = getTushareDailyData($token, "", "20251017", "20251017");			//这样就能查指定某一天的所有股票
	
	// 打印结果
	echo "<pre>";
	print_r($data);
	echo "</pre>";
	
} catch (Exception $e) {
	echo "错误: " . $e->getMessage();
}



/*
数据说明：交易日每天15点～16点之间入库。本接口是未复权行情，停牌期间不提供数据
Array
(
    [request_id] => b429b6d8-070c-45bf-9e6e-25c0869dad8b
    [code] => 0
    [data] => Array
        (
            [fields] => Array
                (
                    [0] => ts_code
                    [1] => trade_date
                    [2] => open
                    [3] => high
                    [4] => low
                    [5] => close
                )

            [items] => Array
                (
                    [0] => Array
                        (
                            [0] => 601288.SH
                            [1] => 20251017
                            [2] => 7.49
                            [3] => 7.69
                            [4] => 7.47
                            [5] => 7.62
                        )

                    [1] => Array
                        (
                            [0] => 601288.SH
                            [1] => 20251016
                            [2] => 7.25
                            [3] => 7.5
                            [4] => 7.23
                            [5] => 7.49
                        )

                    [2] => Array
                        (
                            [0] => 601288.SH
                            [1] => 20251015
                            [2] => 7.11
                            [3] => 7.3
                            [4] => 7.08
                            [5] => 7.27
                        )

                    [3] => Array
                        (
                            [0] => 601288.SH
                            [1] => 20251014
                            [2] => 6.88
                            [3] => 7.13
                            [4] => 6.83
                            [5] => 7.13
                        )

                    [4] => Array
                        (
                            [0] => 601288.SH
                            [1] => 20251013
                            [2] => 6.8
                            [3] => 6.96
                            [4] => 6.73
                            [5] => 6.91
                        )

                    [5] => Array
                        (
                            [0] => 601288.SH
                            [1] => 20251010
                            [2] => 6.7
                            [3] => 6.83
                            [4] => 6.68
                            [5] => 6.83
                        )
					...
*/




